﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace crazy.EntityFrameworkCore.Seed.Goods
{
    public class DefaultGoodsCreator
    {
        private readonly crazyDbContext _context;
        private  List<crazy.Goods.Goods> GoodsList= GetInitialGoods();
        public DefaultGoodsCreator(crazyDbContext context)
        {
            _context = context;
        }
        private static List<crazy.Goods.Goods> GetInitialGoods()
        {
            return new List<crazy.Goods.Goods>
            {
                new crazy.Goods.Goods("商品1",100,"描述1",10),
                new crazy.Goods.Goods("商品2",260,"描述2",50),
                new crazy.Goods.Goods("商品3",99,"描述2",1),
            };
        }
        
        public void Create()
        {
            CreateGoods();
        }
        /// <summary>
        /// 循环添加初始数据
        /// </summary>
        private void CreateGoods()
        {
            foreach (var goods in GoodsList)
            {
                AddGoodsIfNotExists(goods);
            }
        }
        /// <summary>
        /// 判断添加不存在的商品数据
        /// </summary>
        /// <param name="goods"></param>
        private void AddGoodsIfNotExists(crazy.Goods.Goods goods)
        {
            if (_context.Goods.IgnoreQueryFilters().Any(l => l.GoodsName == goods.GoodsName))
            {
                return;
            }

            _context.Goods.Add(goods);
            _context.SaveChanges();
        }
    }
}
